package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.R;
import com.itheima.reggie.util.BaseContext;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
public class LoginCheckFilter implements Filter {
    //执行顺序,才执行filter再执行controller再执行handler
    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws ServletException, IOException {
        System.out.println("过滤器启动....");

        HttpServletRequest request = (HttpServletRequest) req;

        HttpServletResponse response = (HttpServletResponse) res;


        //放行需要放行的请求

        String[] urls = {
                "/employee/login",
                "/backend/**",
                "/front/**",
                "/user/sendMsg",
                "/user/login",
        };


        String requestURI = request.getRequestURI();

//        System.out.println(requestURI);

        boolean flag = check(urls, requestURI);

        if (flag) {
            chain.doFilter(request, response);
            return;
        }

        //剩下的请求判断是否登录

        Long id = (Long) request.getSession().getAttribute("employee");

        if (id != null) {
            BaseContext.setId(id);
            chain.doFilter(request, response);
            return;
        }

        //这里并不冲突,因为用户要么是员工端登录,要么是客户端登录,ThreadLocal域只保存一份值
        Long UserId = (Long) request.getSession().getAttribute("user");

        if (UserId != null) {
            BaseContext.setId(UserId);
            chain.doFilter(request, response);
            return;
        }

        //未登录的请求返回前端响应信息,后端不做页面跳转

        String json = JSON.toJSONString(R.error("NOTLOGIN"));
        response.getWriter().write(json);
        return;


    }

    private boolean check(String[] urls, String requestURI) {

        AntPathMatcher pathMatcher = new AntPathMatcher();

        for (String url : urls) {
            boolean match = pathMatcher.match(url, requestURI);
            if (match) {
                return true;
            }
        }
        return false;
    }
}
